package com.spring.arch.uaa.oauth2.bean;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.spring.arch.common.enums.UserStatus;
import com.spring.arch.common.enums.UserStatus;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.UUID;

/**
 * 安全用户信息
 *
 * @author Frank
 * @version 1.0.0.1
 * @since JDK 1.8
 */
@ToString
@EqualsAndHashCode
public class SecurityUser implements UserDetails {

    private static final long serialVersionUID = 1750420614873555393L;

    @Getter
    private final UUID id;

    /**
     * 用户账号
     */
    @Getter
    private final String account;

    /**
     * 密码
     */
    @JsonIgnore
    private final String password;

    /**
     * 密码盐
     */
    @JsonIgnore
    @Getter
    private final String salt;

    /**
     * 用户手机号
     */
    @Getter
    private final String mobile;

    /**
     * 用户状态
     */
    @Getter
    private UserStatus status;

    @Getter
    private final Collection<? extends GrantedAuthority> authorities;

    public SecurityUser(final UUID id,
                        final String account,
                        final String password,
                        final String salt,
                        final String mobile,
                        final UserStatus status,
                        final Collection<? extends GrantedAuthority> authorities) {
        super();
        this.id = id;
        this.account = account;
        this.password = password;
        this.salt = salt;
        this.mobile = mobile;
        this.status = status;
        this.authorities = authorities;
    }

    @Override
    public String getUsername() {
        return StringUtils.isBlank(this.account) ? this.mobile : this.account;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public boolean isAccountNonExpired() {
        return status != UserStatus.DELETED;
    }

    @Override
    public boolean isAccountNonLocked() {
        return status != UserStatus.LOCKED;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return status != UserStatus.DELETED;
    }

    @Override
    public boolean isEnabled() {
        return status == UserStatus.ACTIVE
                || status == UserStatus.CREATED
                || status == UserStatus.INACTIVE
                || status == UserStatus.TEMP_LOCKED_BAD_CREDENTIALS;
    }
}